package com.heima.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.service.ApUserSearchService;
import com.heima.search.service.ArticleSearchService;
import com.heima.utils.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class ArticleSearchServiceImpl implements ArticleSearchService {


    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Autowired
    private ApUserSearchService apUserSearchService;

    @Autowired
    private MongoTemplate mongoTemplate;


    /**
     * ES文章分页搜寻
     */
    @Override
    public ResponseResult search(UserSearchDto dto) throws IOException {
//        校验参数
        if (dto == null || dto.getSearchWords() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

//        获取用户消息
        ApUser user = AppThreadLocalUtil.getUser();
        if (user != null && dto.getFromIndex() == 0) {
            //        异步保存关键字
            apUserSearchService.insert(dto.getSearchWords(), AppThreadLocalUtil.getUser().getId());
        }

//        设置要查询的对象
        SearchRequest searchRequest = new SearchRequest("app_info_article");
//        封装要查询的条件
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
//        多个条件用户布尔条件封装
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
//        设置查询条件
        QueryStringQueryBuilder queryStringQueryBuilder = QueryBuilders.queryStringQuery(dto.getSearchWords())
                .field("title").field("content").defaultOperator(Operator.OR);
        boolQueryBuilder.must(queryStringQueryBuilder);

//        查询最小时间的文章
        RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("publishTime").lt(dto.getMinBehotTime().getTime());
        boolQueryBuilder.filter(rangeQueryBuilder);

//        分页查询
        sourceBuilder.from(0);
        sourceBuilder.size(dto.getPageSize());

//        时间进行排序
        sourceBuilder.sort("publishTime", SortOrder.DESC);

//        设置高亮显示
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title");
        highlightBuilder.preTags("<font style='color: red; font-size: inherit;'>");
        highlightBuilder.postTags("</font>");
        sourceBuilder.highlighter(highlightBuilder);

//        封装条件
        sourceBuilder.query(boolQueryBuilder);
        searchRequest.source(sourceBuilder);
//        查询数据
        SearchResponse searchData = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

//        封装数据返回,获取所有命中的数据
        SearchHit[] hits = searchData.getHits().getHits();

        List<Map> mapList = new ArrayList<>();

        for (SearchHit hit : hits) {
//            获取数据
            String json = hit.getSourceAsString();
//            转化为map集合
            Map map = JSON.parseObject(json, Map.class);
//            获取高亮数据
            if (hit.getHighlightFields() != null && hit.getHighlightFields().size() > 0) {
//                得到高亮数据并且返回数据
                Text[] titles = hit.getHighlightFields().get("title").getFragments();
//                文本转为json
                String title = StringUtils.join(titles);
//                获取高亮标题
                map.put("h_title", title);
            } else {
//                原始标题
                map.put("h_title", map.get("title"));
            }

            mapList.add(map);

        }
        return ResponseResult.okResult(mapList);
    }

}